#include "AT24CXX.h"


void AT24CXX_Write_Byte(uint8_t *data, uint16_t addr)
{
	uint8_t ret;
	if(MEMTOTAL == 512)
		ret = HAL_I2C_Mem_Write( &hi2c1, ADDR_AT24CXX_DEV, addr, I2C_MEMADD_SIZE_16BIT, data, 1, 1000 );
	else
		ret = HAL_I2C_Mem_Write( &hi2c1, ADDR_AT24CXX_DEV|(((addr&0x07ff)>>8)<<1), addr&0x00ff, I2C_MEMADD_SIZE_8BIT, data, 1, 1000 );
	if( ret != HAL_OK)
	{
		HAL_I2C_DeInit(&hi2c1);
		HAL_I2C_Init(&hi2c1);
	}
	HAL_Delay(5);
}
	
void AT24CXX_Read_Byte(uint8_t *data, uint16_t addr)
{
	uint8_t ret;
	if(MEMTOTAL == 512)
		ret = HAL_I2C_Mem_Read( &hi2c1, ADDR_AT24CXX_DEV, addr, I2C_MEMADD_SIZE_16BIT, data, 1, 1000 );
	else
		ret = HAL_I2C_Mem_Read( &hi2c1, ADDR_AT24CXX_DEV|(((addr&0x07ff)>>8)<<1), addr&0x00ff, I2C_MEMADD_SIZE_8BIT, data, 1, 1000 );
	if( ret != HAL_OK)
	{
		HAL_I2C_DeInit(&hi2c1);
		HAL_I2C_Init(&hi2c1);
	}
	HAL_Delay(5);
}

void AT24CXX_Write_nBytes(uint8_t *data, uint16_t addr, uint16_t length)
{
	uint8_t ret;
	if(MEMTOTAL == 512)
		ret = HAL_I2C_Mem_Write( &hi2c1, ADDR_AT24CXX_DEV, addr, I2C_MEMADD_SIZE_16BIT, data, length, 1000 );
	else
		ret = HAL_I2C_Mem_Write( &hi2c1, ADDR_AT24CXX_DEV|(((addr&0x07ff)>>8)<<1), addr&0x00ff, I2C_MEMADD_SIZE_8BIT, data, length, 1000 );
	if( ret != HAL_OK)
	{
		HAL_I2C_DeInit(&hi2c1);
		HAL_I2C_Init(&hi2c1);
	}
	HAL_Delay(10);
}

void AT24CXX_Read_nBytes(uint8_t *data, uint16_t addr, uint16_t length)
{
	uint8_t ret;
	if(MEMTOTAL == 512)
		ret = HAL_I2C_Mem_Read( &hi2c1, ADDR_AT24CXX_DEV, addr, I2C_MEMADD_SIZE_16BIT, data, length, 1000 );
	else
		ret = HAL_I2C_Mem_Read( &hi2c1, ADDR_AT24CXX_DEV|(((addr&0x07ff)>>8)<<1), addr&0x00ff, I2C_MEMADD_SIZE_8BIT, data, length, 1000 );
	if( ret != HAL_OK)
	{
		HAL_I2C_DeInit(&hi2c1);
		HAL_I2C_Init(&hi2c1);
	}
	HAL_Delay(10);
}
